#include <iostream>
#include <boost/filesystem.hpp>
#include "json_parser.h"
#include "json2mtl.h"
#include "bin2obj.h"
#include "convert.h"

int _convert(const char *jsonPath, const char *targetDir)
{
    if (!boost::filesystem::exists(jsonPath))
    {
        std::cerr << "jsonPath is not existed: " << jsonPath << std::endl;
        return -1;
    }
    if (!boost::filesystem::exists(targetDir))
    {
        boost::filesystem::create_directories(targetDir);
    }
    JsonFile jsonFile = parseBinJsonFile(jsonPath);

    boost::filesystem::path jsonFilePath = jsonPath;
    boost::filesystem::path jsonFileDir = jsonFilePath.parent_path();
    boost::filesystem::path fileName = jsonFilePath.filename();
    boost::filesystem::path extension = jsonFilePath.extension();
    fileName.replace_extension();

    boost::filesystem::path binPath = jsonFileDir;
    binPath.concat("/").concat(jsonFile.Buffers);
    boost::filesystem::path targetFileDir = targetDir;
    targetFileDir.remove_trailing_separator();
    boost::filesystem::path objPath = targetFileDir;
    objPath.concat("/").concat(fileName.string()).concat(".obj");
    boost::filesystem::path mtlPath = targetFileDir;
    mtlPath.concat("/").concat(fileName.string()).concat(".mtl");

    bin2obj(jsonFile, binPath.string().c_str(), objPath.string().c_str());
    json2mtl(jsonFile, mtlPath.string().c_str());

    // boost::filesystem::directory_iterator ite_begin(jsonFileDir);
    // std::cout << "123" << std::endl;
    // boost::filesystem::directory_iterator ite_end;
    // for (; ite_begin != ite_end; ite_begin++)
    // {
    //     boost::filesystem::path child = *ite_begin;
    //     if (!boost::filesystem::is_regular_file(child) || boost::filesystem::is_directory(child))
    //     {
    //         continue;
    //     }
    //     std::cout << child.string() << std::endl;
    //     std::string fileName = child.filename().string();
    //     std::string extension = child.extension().string();
    //     if (extension == ".png" || extension == ".jpg" || extension == ".jpeg")
    //     {
    //         boost::filesystem::path targetPath = targetDir;
    //         targetPath /= fileName;
    //         boost::filesystem::copy(child, targetPath);
    //     }
    // }

    std::cout << "convert " << jsonPath << " to obj done" << std::endl;

    return 0;
}

int convert(const char *jsonPath, const char *targetDir)
{
    return _convert(jsonPath, targetDir);
}